package com.demo01_video.controller;

import com.demo01_video.bean.Video;
import com.demo01_video.repository.VideoRepository;
import com.demo01_video.service.VideoService;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import jakarta.servlet.http.HttpServletRequest;

//创建VideoController控制器，用于处理视频发布的请求
@RestController
@RequestMapping("/videos")
@RequiredArgsConstructor
@Slf4j
public class VideoController {
    private final VideoService videoService;
    private final VideoRepository videoRepository;

    @PostMapping("/publish")
    public ResponseEntity<String> publishVideo(@RequestParam("file") MultipartFile file,
                                               @RequestParam("title") String title,
                                               HttpServletRequest request) {
        // 从请求头中获取用户ID（由API网关解析JWT Token后传递）
        String userIdStr = request.getHeader("user-id");
        if (userIdStr == null || userIdStr.isEmpty()) {
            return ResponseEntity.badRequest().body("缺少用户ID");
        }
        
        try {
            Long authorId = Long.parseLong(userIdStr);
            log.info("开始发布视频，标题：{}，用户ID：{}", title, authorId);
            videoService.publishVideo(file, title, authorId);
            log.info("视频发布成功，标题：{}，用户ID：{}", title, authorId);
            return ResponseEntity.ok("视频发布成功");
        } catch (IOException e) {
            log.error("视频发布失败: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body("视频发布失败: " + e.getMessage());
        } catch (NumberFormatException e) {
            log.error("用户ID格式错误: {}", e.getMessage(), e);
            return ResponseEntity.badRequest().body("用户ID格式错误");
        } catch (Exception e) {
            log.error("视频发布过程中出现未知错误: {}", e.getMessage(), e);
            return ResponseEntity.status(500).body("视频发布失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/search")
    public ResponseEntity<Iterable<Video>> searchVideos(@RequestParam("title") String title) {
        // 处理非分片键查询示例
        Iterable<Video> videos = videoService.searchVideosByTitle(title);
        return ResponseEntity.ok(videos);
    }
    
    @GetMapping("/{videoId}/status")
    public ResponseEntity<VideoStatusResponse> getVideoStatus(@PathVariable Long videoId) {
        Video video = videoRepository.findById(videoId)
                .orElseThrow(() -> new RuntimeException("视频不存在"));
        
        VideoStatusResponse response = new VideoStatusResponse();
        response.setVideoId(videoId);
        response.setStatus(video.getStatus()); // 0-待转码, 1-转码中, 2-成功, 3-失败
        response.setVideoUrl(video.getVideoUrl()); // 转码成功后才有值
        
        return ResponseEntity.ok(response);
    }
    
    @Data
    public static class VideoStatusResponse {
        private Long videoId;
        private Integer status; // 0-待转码, 1-转码中, 2-成功, 3-失败
        private String videoUrl;
    }
}